package com.alipay.service.impl;

import com.alipay.constants.Constants;
import com.alipay.mapper.RedBagMapper;
import com.alipay.model.dto.ImDto;
import com.alipay.model.dto.SendSuccessDto;
import com.alipay.model.enums.QueueEnum;
import com.alipay.model.enums.RedBagStatusEnum;
import com.alipay.service.CallbackService;
import com.alipay.service.rpc.ImService;
import com.alipay.util.DateUtil;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 *
 * @author Jun
 * @date 2019/3/23
 */
@Service
public class CallbackServiceImpl implements CallbackService{

    @Autowired
    private RedBagMapper redBagMapper;

    @Autowired
    private ImService imService;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Override
    public void sendSuccessCallBack(SendSuccessDto sendSuccessDto) {
        Date expireTime = DateUtil.getHoursLater(-Constants.EXPIRE_HOUR);

        // 乐观锁并发控制防重、幂等
        boolean flag = redBagMapper.updateStatusAndExpireTime(sendSuccessDto.getRedBagNo(), RedBagStatusEnum.INIT.getStatus(), RedBagStatusEnum.NORMAL.getStatus(),expireTime);

        if (flag) {
            // 调用IM服务通知群用户抢红包了
            imService.noticeGroup(new ImDto());

            // 使用rabbit mq实现延迟队列，延迟24小时之后通知消费者检查是否需要退款给发送红包的用户
            // 此处需要实现mq的ack确认机制，保证消息成功发送
            rabbitTemplate.convertAndSend(
                    QueueEnum.DELAY_QUEUE.getName(),
                    sendSuccessDto.getRedBagNo(),
                    msg -> {
                        msg.getMessageProperties()
                                .setExpiration(String.valueOf(expireTime.getTime() - System.currentTimeMillis()));
                        return msg;
                    });
        }
    }
}
